<?php
/**
* @author: Trần Ngọc Thắng
* @link: fb.com/tranngoc8x
* @email: tranngocthang89@gmail.com
**/


App::uses('ManagerAppController', 'Manager.Controller');
App::uses('Folder', 'Utility');
class ModulesController extends ManagerAppController {

	public $uses = null;
	public $scaffold;
	public function admin_index() {
		$plugins = array();
		$this->folder = new Folder;
		$pluginPaths = App::path('plugins');
		foreach ($pluginPaths as $pluginPath) {
			$this->folder->path = $pluginPath;
			if (!file_exists($this->folder->path)) {
				continue;
			}
			$pluginFolders = $this->folder->read();
			//debug($pluginPath);
			foreach ($pluginFolders[0] as $pluginFolder) {
				if (substr($pluginFolder, 0, 1) != '.') {
					if (!$this->_isCorePlugin($pluginPath, $pluginFolder)) {
						continue;
					}
					$plugins[$pluginFolder] = $this->_getdata($pluginFolder);
				}
			}
		}
		$this->set(compact('plugins'));
	}
	protected function _isCorePlugin($path,$folder){
		$dir = $path . $folder . DS;
		if (file_exists($dir . 'Config' . DS . 'plugin.json')) {
			return true;
		}
		return false;
	}
	protected function _getdata($alias = null){
		$pluginPaths = App::path('plugins');
		foreach ($pluginPaths as $pluginPath) {
			$active = $this->isActive($alias);
			$isCroogoPlugin = false;
			$manifestFile = $pluginPath . $alias . DS . 'Config' . DS . 'plugin.json';
			$hasManifest = file_exists($manifestFile);
			$composerFile = $pluginPath . $alias . DS . 'composer.json';
			$hasComposer = file_exists($composerFile);
			if ($hasManifest || $hasComposer) {
				$pluginData = array(
					'name' => $alias,
					'active' => $active,
				);

				if ($hasManifest) {
					$manifestData = json_decode(file_get_contents($manifestFile), true);
					if (empty($manifestData)) {
						$this->log($alias . 'plugin.json exists but cannot be decoded.');
						return $pluginData;
					}
					$pluginData = array_merge($manifestData, $pluginData);
				}
			}
			return $pluginData;
		}
		return false;
	}
	protected function isActive($plugin) {
		$configureKeys = array(
			'Plugins.extend',
		);
		$plugin = array(Inflector::underscore($plugin), Inflector::camelize($plugin));
		foreach ($configureKeys as $configureKey) {
			$hooks = explode(',', Configure::read($configureKey));
			foreach ($hooks as $hook) {
				if (in_array($hook, $plugin)) {
					return true;
				}
			}
		}
		return false;
	}
/**
 * admin_add
 *
 * @return void
 */
	public function admin_add() {
		$this->set('title_for_layout', __d('croogo', 'Upload a new plugin'));

		if (!empty($this->request->data)) {
			$file = $this->request->data['Plugin']['file'];
			unset($this->request->data['Plugin']['file']);

			$Installer = new ExtensionsInstaller;
			try {
				$Installer->extractPlugin($file['tmp_name']);
			} catch (CakeException $e) {
				$this->Session->setFlash($e->getMessage(), 'flash', array('class' => 'error'));
				return $this->redirect(array('action' => 'add'));
			}
			return $this->redirect(array('action' => 'index'));
		}
	}

/**
 * admin_delete
 *
 * @param string $plugin
 * @return void
 */
	public function admin_delete($plugin = null) {
		if (!$plugin) {
			$this->Session->setFlash(__d('manager', 'Invalid plugin'), 'flash', array('class' => 'error'));
			return $this->redirect(array('action' => 'index'));
		}
		if ($this->_CroogoPlugin->isActive($plugin)) {
			$this->Session->setFlash(__d('manager', 'You cannot delete a plugin that is currently active.'), 'flash', array('class' => 'error'));
			return $this->redirect(array('action' => 'index'));
		}

		$result = $this->_delete($plugin);
		if ($result === true) {
			$this->Session->setFlash(__d('manager', 'Plugin "%s" deleted successfully.', $plugin), 'flash', array('class' => 'success'));
		} elseif (!empty($result[0])) {
			$this->Session->setFlash($result[0], 'flash', array('class' => 'error'));
		} else {
			$this->Session->setFlash(__d('manager', 'Plugin could not be deleted.'), 'flash', array('class' => 'error'));
		}

		return $this->redirect(array('action' => 'index'));
	}
	protected function _delete($plugin) {
		if (empty($plugin)) {
			throw new InvalidArgumentException(__d('manager', 'Invalid plugin'));
		}
		$pluginPath = APP . 'Plugin' . DS . $plugin;
		if (is_link($pluginPath)) {
			return unlink($pluginPath);
		}
		$folder = new Folder();
		$result = $folder->delete($pluginPath);
		if ($result !== true) {
			return $folder->errors();
		}
		return true;
	}

	public function admin_active($plugin){
		$this->addBootstrap($plugin);
		CakePlugin::load($plugin);
		Cache::delete('file_map', '_cake_core_');
		$this->render= false;
		$this->autoRender= false;
		$this->redirect(array('action'=>'index'));
	}
	public function admin_deactive($plugin){
		if (!CakePlugin::loaded($plugin)) {
			return __d('manager', 'Plugin "%s" is not active.', $plugin);
		}
		$this->removeBootstrap($plugin);
		CakePlugin::unload($plugin);
		Cache::delete('file_map', '_cake_core_');
		$this->render= false;
		$this->autoRender= false;
		$this->redirect(array('action'=>'index'));
	}
	public function removeBootstrap($plugin) {
		$hookBootstraps = Configure::read('Plugins.extend');
		if (!$hookBootstraps) {
			return;
		}

		$plugins = explode(',', $hookBootstraps);
		$names = array(Inflector::underscore($plugin), Inflector::camelize($plugin));
		if ($intersect = array_intersect($names, $plugins)) {
			$plugin = current($intersect);
			$k = array_search($plugin, $plugins);
			unset($plugins[$k]);
		}
		$this->_saveBootstraps($plugins);
	}

	public function addBootstrap($plugin) {
		$hookBootstraps = Configure::read('Plugins.extend');
		if (!$hookBootstraps) {
			$plugins = array();
		} else {
			$plugins = explode(',', $hookBootstraps);
			$names = array(Inflector::underscore($plugin), Inflector::camelize($plugin));
			if ($intersect = array_intersect($names, $plugins)) {
				$plugin = current($intersect);
			}
		}

		if (array_search($plugin, $plugins) !== false) {
			$plugins = (array)$hookBootstraps;
		} else {
			$plugins[] = $plugin;
		}
		$this->_saveBootstraps($plugins);
	}

	protected function _saveBootstraps($plugins) {
		$settings = array(
			'Site'=>Configure::read('Site'),
			'Plugins'=>Configure::read('Plugins'),
			'Meta'=>Configure::read('Meta'),
			'Service'=>Configure::read('Service')
		);
		$settings['Plugins']['extend'] = implode(',', $plugins);
		Configure::write($settings);
		foreach ($settings as $key => $setting) {
			//list($key, $ignore) = explode('.', $key, 2);
			$keys[] = $key;
		}
		$keys = array_unique($keys);
		Configure::dump('settings.json', 'settings', $keys);
		Configure::load('settings', 'settings');

	}

	public function admin_move()
	{
		# code...
	}
}
